#!/bin/bash
RM=/bin/rm
TAR=/bin/tar
MONGO=/bin/mongo
DATE=`/bin/date '+%Y%m%d_%H%M%S'`
FIND=/bin/find
RCLONE=/bin/rclone
TMPFILE="/tmp/mongodb-backup-runner.$$.tmp"

if [ ! -d {{ mongod_path }}/backup/mongod/temp ]; then
  echo "Backup destination folder: {{ mongod_path }}/backup/mongod/temp does not exist."
  exit 0
else
  $RM -fr {{ mongod_path }}/backup/mongod/temp/*
fi

$MONGO --host {{ ansible_default_ipv4.address }} --port {{ mongod_port }}{% if mongod_ssl | bool %} --ssl --sslAllowInvalidHostnames --sslAllowInvalidCertificates{% endif %} -u "backup" -p "{{ mongod_backup_user_passwd }}" --authenticationDatabase "admin" admin << EOF
  db.runCommand({createBackup: 1, backupDir: "{{ mongod_path }}/backup/mongod/temp"});
EOF

echo $?
if [ $? = 0 ]; then
$TAR zcvfP - {{ mongod_path }}/backup/mongod/temp/* --remove-files | openssl aes-256-cbc -salt -k '{{ mongod_backupset_arg.encryptkey | default("changeme") }}' -out {{ mongod_path }}/backup/mongod/full_$DATE.tar.gz >> $TMPFILE 2>&1
fi

$FIND {{ mongod_path }}/backup/mongod -type f -mtime +{{ mongod_backupset_arg.keep }} -exec $RM -fr {} \;

{% if mongod_backupset_arg.cloud_rsync | bool and mongod_backupset_arg.cloud_drive is defined %}
# Rsync for cloud storage
$RCLONE --no-check-certificate --verbose --config="/etc/rclone/mongod.conf" mkdir mongod:{{ ansible_hostname | lower }} >> $TMPFILE 2>&1
$RCLONE --no-check-certificate --bwlimit="{{ mongod_backupset_arg.cloud_bwlimit | default('10M') }}" --verbose --config="/etc/rclone/mongod.conf" {{ mongod_backupset_arg.cloud_event | default('sync') }} {{ mongod_path }}/backup/mongod mongod:{{ ansible_hostname | lower }}/mongod >> $TMPFILE 2>&1
{% endif %}
exit 0
